package cn.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 线程池
 *
 * @author duxiaod
 * @date 2021/07/25 20:27
 **/
@RestController
@Slf4j
public class ThreadPoolController {

    @Resource(name = "consumerQueueThreadPool")
    private ExecutorService consumerQueueThreadPool;

    @Resource(name = "providerQueueThreadPool")
    private ExecutorService providerQueueThreadPool;

    @GetMapping("/threadPool")
    public String threadPool() throws InterruptedException {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 50; i++) {
            consumerQueueThreadPool.execute(()->{
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                log.info(Thread.currentThread().getName());
            });

            providerQueueThreadPool.execute(()->{
                log.info(Thread.currentThread().getName());
            });
        }
        // shutdown()执行后停止接受新任务，会把队列的任务执行完毕。
        // shutdownNow() 也是停止接受新任务，但会中断所有的任务，将线程池状态变为 stop。
        consumerQueueThreadPool.shutdown();
        // 会每隔一秒钟检查一次是否执行完毕（状态为 TERMINATED），当从 while 循环退出时就表明线程池已经完全终止了。
        while (!consumerQueueThreadPool.awaitTermination(1, TimeUnit.SECONDS)){
            log.info("线程还在执行。。。");
        }
        long end = System.currentTimeMillis();
        log.info("一共处理了【{}】", (end - start));
        return "ok";
    }
}
